package com.hxx.service.impl;

import com.hxx.domain.TUser;
import com.hxx.mapper.UserMapper;
import com.hxx.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.*;

public class UserServiceImpl implements UserService {
    static SqlSession sqlSession;
    static {
        try {
            //读取Mybatis配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //基于读取Mybatis配置文件的输入流创建SqlSessionFactory对象
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
            //获取SqlSession对象
            sqlSession = build.openSession();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    @Override
    public void save(TUser user) {
        mapper.insertUser(user);
        sqlSession.commit();
    }

    @Override
    public void delete(int id) {
        mapper.deleteUser(id);
        sqlSession.commit();
    }

    @Override
    public void update(TUser user) {
        //使用了Mybatis的API
        sqlSession.update("com.hxx.mapper.UserMapper.updateHxxUser",user);
        sqlSession.commit();
    }

    @Override
    public TUser findById(int id) {
        return mapper.getUserById(id);
    }

    @Override
    public List<TUser> findAll() {
        return mapper.getAllUser();
    }

    @Override
    public List<TUser> findByPage(int page, int pageSize) {
       /* Map<String, Integer> map = new HashMap<>();
        map.put("pageNo",page);
        map.put("pageSize",pageSize);*/
        Map<String, Integer> map =
                Map.of("pageNo",(page-1)*pageSize,"pageSize",pageSize);
        return mapper.getUserByPage(map);
    }

    @Override
    public int getRows() {
        return mapper.getTotal();
    }
}
